﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using LowLevelGraphics;
using LowLevelGraphics.Filter;

using ImageRecognition2.Forms;

namespace ImageRecognition2.Action
{
    /// <summary>
    /// This is used for two source filters (all filters that got an ITwoSourceFilter interface)
    /// </summary>
    public class ActionTwoSourceFilters : AbstractCommand
    {
        protected ITwoSourceFilter m_Filter = null;

        /// <summary>
        /// Initializes a new instance of the <see cref="ActionTwoSourceFilters"/> class.
        /// </summary>
        /// <param name="_filter">The _filter.</param>
        public ActionTwoSourceFilters(ITwoSourceFilter _filter)
        {
            m_Filter = _filter;
        }

        /// <summary>
        /// Runs the specified sender.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public override void Run(object sender, EventArgs e)
        {
            Composing(m_Filter);
        }

        /// <summary>
        /// Composings the specified _filter.
        /// </summary>
        /// <param name="_filter">The _filter.</param>
        private void Composing(ITwoSourceFilter _filter)
        {
            Image mainFormSingletonActivePictureBoxBackgroundImage = MainFormSingleton.ActivePictureBox.BackgroundImage;
            FormChildList childList = new FormChildList();
            if (childList.ShowDialog() != DialogResult.OK) return;
            
            FormItem item = childList.FormItem;
            if (item == null) return;
            
            Image image = item.Form.pictureBox1.BackgroundImage;
            
            if (image == mainFormSingletonActivePictureBoxBackgroundImage)
            {
                MessageBox.Show("Please choose different pictures", "Result");
                return;
            }

            UnsafeBitmap bitmapSource = mainFormSingletonActivePictureBoxBackgroundImage;
            UnsafeBitmap imageSource = image;
            
            UnsafeBitmap bitmap = m_Filter.Process(bitmapSource, imageSource);
            imageSource.Dispose();
            bitmapSource.Dispose();
            bitmap.Dispose();
            
            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmap.InternalBitmap;
            MainFormSingleton.ActivePictureBox.Invalidate();
        }
    }
}
